package com.huixue.cn.ztej.utils.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.huixue.cn.ztej.bean.LoginLogger;
import com.huixue.cn.ztej.bean.Resource;
import com.huixue.cn.ztej.bean.User;
import com.huixue.cn.ztej.dao.LoginLoggerMapper;
import com.huixue.cn.ztej.dao.ResourceMapper;
import com.huixue.cn.ztej.dao.RoleResourceMapper;
import com.huixue.cn.ztej.utils.RemoteUtils;

public class ResouceIntercepter implements HandlerInterceptor{

	@Autowired
	private ResourceMapper resourceDao;
	
	@Autowired
	private LoginLoggerMapper loginLoggerMapper;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURI().replace(request.getContextPath(), "").replaceFirst("/", "");
		//System.out.println(url);
		if(url!=null && url.length()>1){
			Resource resource = resourceDao.selectByUrl(url);
			if(resource==null && request.getSession().getAttribute("currentRes")!=null){
				resource = (Resource)(request.getSession().getAttribute("currentRes"));
			}else if(resource==null){
				resource =  new Resource();
			}
			request.getSession().setAttribute("currentRes", resource);
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		// 获取IP
		String url = request.getRequestURI().replace(request.getContextPath(), "").replaceFirst("/", "");
		String ip = RemoteUtils.getRemoteHost(request);	
		if(request.getSession().getAttribute("loginUser")!=null){
			User user = (User)request.getSession().getAttribute("loginUser");
			LoginLogger logger = new LoginLogger(user.getLoginName(),user.getUserName(),ip,new Date(),1,url);
			if(url.equals("sys/login")){
				logger.setType(1);
				logger.setUrl("sys/login");
			}else if(url.equals("sys/logout")){
				logger.setType(2);
				logger.setUrl("sys/logout");
			}else{
				logger.setType(3);
			}
			loginLoggerMapper.addLogger(logger);
		}
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		
	}
	
	

}
